package io.renren.modules.mail;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.renren.common.utils.MailUtil;
import io.renren.common.utils.R;
import io.renren.common.utils.SendMailUtils;
import io.renren.modules.sys.entity.SysEmailEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.MailService;
import io.renren.modules.sys.service.SysEmailService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/mpq")
public class MailApiController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private Environment env;
//    @Resource
//    private JavaMailSenderImpl sender;
    @Autowired
    private MailService mailService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysEmailService sysEmailService;

    @RequestMapping(value = "/send")
    public R send(){
        String subject = "嗨咯";
        String sendHtml = "测试发送邮箱功能";
        String receiveUser = "1145801282@qq.com";
        MailUtil.receiveEmail(env.getProperty("mail.from"),env.getProperty("mail.host"),env.getProperty("mail.password"));
        return MailUtil.sendEmail(subject,sendHtml,receiveUser);
    }

    @RequestMapping(value = "/sendMail")
    public R sendMail(String username){
        try {
            SysUserEntity sysUserEntity = sysUserService.selectOne(new EntityWrapper<SysUserEntity>()
                    .eq("username",username)
                    .eq("status",1)
            );
            if (sysUserEntity==null){
                return R.error("该账号不存在");
            }
            String mail = sysUserEntity.getEmail();
            if (StringUtils.isBlank(mail)){
                return R.error("你还没有绑定邮箱");
            }
            String[] tos = {mail};
            String subject = "修改密码之验证码";
            int code = (int)((Math.random()*9+1)*100000);
            String codeStr = String.valueOf(code);
            Long userId = sysUserEntity.getUserId();
            SysEmailEntity sysEmailEntity = sysEmailService.selectOne(new EntityWrapper<SysEmailEntity>()
                    .eq("user_id",userId)
            );
            long time = 5*60*1000;//5分钟
            Date afterDate = new Date(new Date() .getTime() + time);//5分钟后的时间
            if (sysEmailEntity==null){
                SysEmailEntity sysEmail = new SysEmailEntity();
                sysEmail.setUpdateTime(afterDate);
                sysEmail.setUserId(sysUserEntity.getUserId());
                sysEmail.setCode(codeStr);
                sysEmailService.insert(sysEmail);
            }else {
                sysEmailEntity.setUpdateTime(afterDate);
                sysEmailEntity.setCode(codeStr);
                sysEmailEntity.setUseful(0);
                sysEmailService.updateById(sysEmailEntity);
            }
            logger.info("进入发送邮箱");
            String username1 = sysUserEntity.getUsername();
            String text ="<body>" +
                    "<p>" +"【明少帥小程序】您正在使用明少帥小程序后台修改密码操作，您的账号为："+username1+";验证码"+codeStr+"，" +
                    "请在5分钟内完成验证，请勿将验证码泄露给他人。该后台由明平强开发，平台不收取任何费用。请您放心使用!" +
                    "明平强为了表示感谢您使用该平台，请您欣赏该美女作为福利。欢迎登陆网站：www.mingpingqiang.top" +
                    "<a href='www.mingpingqiang.top'></a>" +
                    ";或者在微信小程序搜索中明平强或明少帥即可体验明平强开发的小程序哟" +
                    "</p>" +
                    "<img src='https://timgsa.baidu.com/timg?image&quality=80&" +
                    "size=b9999_10000&sec=1533302772280&di=0b3b0a4465763d656add87504464be45" +
                    "&imgtype=0&src=http%3A%2F%2Fxnnews.com.cn%2Fwenyu%2Flxsj%2F201710%2FW020171030786965608760.jpg'/>" +
                    "</body>";
            SendMailUtils.sendTextWithHtml(mailService.newSender(),tos, subject, text);
            logger.info("发送邮箱成功");
        }catch (Exception e){
            logger.error("发送邮箱失败=={}",e.getMessage());
            e.printStackTrace();
            return R.error("发送异常,请联系明平强");
        }
        return R.ok();
    }

}